<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--contain-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            @input="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :span="4" @click="addUserVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--表格区域-->
      <template>
        <el-table :data="userList" stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template v-slot:default="scope">
              <el-switch v-model="scope.row.mg_state" @change="changeUserStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot:default="scope">
              <!--修改按钮-->
              <el-button
                type="primary"
                icon="el-icon-edit"
                v-model="scope.row"
                size="small"
                @click="showEditUser(scope.row.id)"
              ></el-button>
              <!--删除按钮-->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="delMessageBox(scope.row.id)"
              ></el-button>
              <!--分配角色按钮-->
              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="small"
                  @click="powerUser(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!--添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addUserVisible" width="50%" @closed="resetAddUser">
      <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑用户对话框-->
    <el-dialog title="编辑用户" :visible.sync="editUserVisible" width="50%" @closed="resetEditUser">
      <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitEditUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--分配用户权限对话框-->
    <el-dialog title="分配角色" :visible.sync="powerVisible" width="50%" @closed="resetSelectRole">
      <p>当前的用户：{{userInfo.username}}</p>
      <p>当前的角色：{{userInfo.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in selectInfo"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer">
        <el-button @click="powerVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitPowerUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 表单二次校验
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入正确的电话号码'))
      }
    }
    return {
      // 用户列表请求数据
      queryInfo: {
        query: '',
        pagenum: '1',
        pagesize: '2'
      },
      // 用户列表响应数据
      userList: [],
      total: 0,
      // 是否显示添加用户对话框
      addUserVisible: false,
      // 是否显示编辑用户对话框
      editUserVisible: false,
      powerVisible: false,
      // 添加用户表单对象
      addUserForm: { username: '', password: '', eamil: '', mobile: '' },
      editUserForm: {},
      // 分配权限用户信息
      userInfo: {},
      // 分配权限下拉菜单
      selectInfo: [],
      selectRoleId: '',
      // 添加用户表单校验
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3到10个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],

        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],

        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户数据列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取管理员列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 改变用户状态
    async changeUserStatus(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 每页显示条数
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 当前页数
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 重置添加用户表单
    resetAddUser() {
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserRef.validate(async val => {
        // 验证失败不执行后续代码
        if (!val) return false
        // 发起请求添加用户
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          this.$message.error('用户添加失败')
        } else {
          this.$message.success('用户添加成功')
          // 关闭对话框
          this.addUserVisible = false
          // 重新获取用户列表
          this.getUserList()
        }
      })
    },
    // 编辑用户
    async showEditUser(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        this.$message.error('编辑用户失败！')
        return false
      }
      this.editUserForm = res.data
      this.editUserVisible = true
    },
    // 移除编辑用户校验效果
    resetEditUser() {
      this.$refs.editUserRef.clearValidate()
    },
    // 提交修改用户信息
    commitEditUser() {
      this.$refs.editUserRef.validate(async val => {
        if (!val) {
          return false
        } else {
          // 重新请求更新用户信息
          const { data: res } = await this.$http.put(
            `users/${this.editUserForm.id}`,
            {
              email: this.editUserForm.email,
              mobile: this.editUserForm.mobile
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('更新用户信息失败！')
            return false
          }
          this.$message.success('更新用户信息成功！')
          // 重新获取用户列表
          this.getUserList()
          // 关闭对话框
          this.editUserVisible = false
        }
      })
    },
    // 删除用户对话框
    async delMessageBox(id) {
      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 确定
        .then(async () => {
          // 通过id删除对应的用户
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('用户删除失败！')
          }
          this.$message.success('删除成功！')
          if (this.userList.length === 1) {
            this.queryInfo.pagenum--
          }
          this.getUserList()
        })
        // 取消
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },
    async powerUser(user) {
      this.powerVisible = true
      this.userInfo.id = user.id
      this.userInfo.role_name = user.role_name
      this.userInfo.username = user.username
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色列表获取失败！')
      }
      this.selectInfo = res.data
    },
    async commitPowerUser() {
      if (!this.selectRoleId) {
        return this.$message.warning('请选择角色！')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectRoleId
        }
      )
      if (res.meta.status === 400) {
        return this.$message.warning('不允许修改admin用户！')
      }
      if (res.meta.status !== 200) return this.$message.error('设置角色失败！')
      this.getUserList()
      this.powerVisible = false
    },
    resetSelectRole() {
      this.selectRoleId = ''
    }
  }
}
</script>
